package com.tianji.login.service;

import com.alibaba.fastjson.JSON;
import com.tianji.config.EsClientConfig;
import com.tianji.login.pojo.SysUser;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ESService {

    public void bulkInsert(List<SysUser> users) throws IOException {
        BulkRequest request = new BulkRequest();
        for(SysUser user:users){
            String docId = user.getUserId().toString();
            //幂等性处理
            GetRequest getRequest = new GetRequest("userId", docId);
            boolean exists = EsClientConfig.client().exists(getRequest, RequestOptions.DEFAULT);
            if(!exists){
                request.add(new IndexRequest("user")
                        .id(docId)
                        .source(JSON.toJSONString(user), XContentType.JSON));
            }
        }
        if(request.numberOfActions() > 0){
            EsClientConfig.client().bulk(request,RequestOptions.DEFAULT);
        }else{
            System.out.println("所有文档已经存在，无需导入");
        }
    }
}
